﻿using AutoMapper;
using B.Rabbit.DataBase.Domain;
using B.Rabbit.DataBase.ErrorCode;
using B.Rabbit.DataBase.Infrastructure.Infrastructure;
using B.Rabbit.DataBase.Read.Api.Applocation.Command.Rabbit.Traceab;
using B.Rabbit.DataBase.Read.Api.Applocation.Handler.Login;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.Rabbit.DataBase.Read.Api.Applocation.Handler.Rabbit.Traceab
{
    public class AddTraceabCommandHandler : IRequestHandler<AddTraceabCommand, ApiResult<int>>
    {
        IBaseRepository<TraceabilityModel> traceabmodel;
        IBaseRepository<LogModel> logmodel;
        private readonly ILogger<AddTraceabCommandHandler> _logger;
        IMapper mapper;

        public AddTraceabCommandHandler(IBaseRepository<TraceabilityModel> traceabmodel, IBaseRepository<LogModel> logmodel, ILogger<AddTraceabCommandHandler> logger, IMapper mapper)
        {
            this.traceabmodel = traceabmodel;
            this.logmodel = logmodel;
            _logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 溯源信息处理类
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(AddTraceabCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("溯源信息添加操作");
            ApiResult<int> res = new ApiResult<int>();
            var entity = mapper.Map<TraceabilityModel>(request);
            entity.Id = YitIdHelper.NextId();
            entity.CreateName = "张三";
            entity.UpdateName = "张三";
            entity.CreateTime = DateTime.Now;
            var r1 = await traceabmodel.AddAsync(entity);

            if (r1>0)
            {
                res.data = r1;
                res.msg = "添加成功";
                res.code = StatusCode.Ok;
            }
            else
            {
                res.data = r1;
                res.msg = "添加失败";
                res.code = StatusCode.Fail;
            }
            return res;
        }
    }
}
